#!/bin/bash

# 基于CSDN博客的matplotlib中文字体修复脚本
# 参考: https://blog.csdn.net/xiaoyw71/article/details/119699910

echo "=== 基于CSDN博客的matplotlib中文字体修复方案 ==="
echo "参考: https://blog.csdn.net/xiaoyw71/article/details/119699910"

# 1. 检查matplotlib路径
echo "1. 检查matplotlib路径..."
python3 -c "
import matplotlib
print('matplotlib配置文件路径:', matplotlib.matplotlib_fname())
"

# 2. 检查系统字体
echo "2. 检查系统字体..."
echo "系统字体目录:"
ls -la /usr/share/fonts/chinese/ 2>/dev/null || echo "chinese目录不存在"
ls -la /usr/share/fonts/google-noto-cjk/ 2>/dev/null || echo "google-noto-cjk目录不存在"

# 3. 更新字体缓存
echo "3. 更新字体缓存..."
if command -v fc-cache &> /dev/null; then
    fc-cache -fv
    echo "✓ 系统字体缓存更新完成"
else
    echo "⚠️  fc-cache命令不存在，跳过系统字体缓存更新"
fi

# 4. 清除matplotlib缓存
echo "4. 清除matplotlib缓存..."
python3 -c "
import matplotlib
import os
cache_dir = matplotlib.get_cachedir()
print('matplotlib缓存目录:', cache_dir)
cache_files = ['fontlist-v330.json', 'fontlist-v320.json', 'fontlist-v310.json', 'fontlist-v300.json']
for cache_file in cache_files:
    cache_path = os.path.join(cache_dir, cache_file)
    if os.path.exists(cache_path):
        os.remove(cache_path)
        print('✓ 删除缓存文件:', cache_file)
"

# 5. 重建matplotlib字体缓存
echo "5. 重建matplotlib字体缓存..."
python3 -c "
import matplotlib.font_manager as fm
fm._rebuild()
print('✓ matplotlib字体缓存重建完成')
"

# 6. 运行完整修复脚本
echo "6. 运行完整修复脚本..."
python3 comprehensive_font_fix.py

# 7. 验证修复结果
echo "7. 验证修复结果..."
if [ -f "comprehensive_font_test.png" ]; then
    echo "✓ 测试图片生成成功"
    echo "请检查 comprehensive_font_test.png 文件"
else
    echo "⚠️  测试图片生成失败"
fi

# 8. 显示最终状态
echo "8. 显示最终状态..."
python3 -c "
import matplotlib.font_manager as fm
all_fonts = [f.name for f in fm.fontManager.ttflist]
chinese_fonts = [f for f in all_fonts if any(kw in f.lower() for kw in ['chinese', 'han', 'cjk', 'wenquanyi', 'noto', 'source'])]
print(f'识别到 {len(chinese_fonts)} 个中文字体:')
for font in chinese_fonts[:5]:
    print(f'  - {font}')
"

echo ""
echo "=== 修复完成 ==="
echo "现在可以运行你的Python脚本了: python3 card_clients.py"
echo ""
echo "📋 如果仍有问题，请尝试:"
echo "1. 重启Python环境"
echo "2. 运行: python3 -c \"import matplotlib; matplotlib.font_manager._rebuild()\""
echo "3. 检查生成的测试图片"
